from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from goods.models import SKUImage, SKU
from meiduo_admin.serializers.skuimages_serializers import SKUImageSerializer, SKUSimpleSerializer
from meiduo_admin.utils import MyPagination
from rest_framework.decorators import action
from rest_framework.response import Response


# class SKUSimpleView(ListAPIView):
#     """ 获取sku名称 --- 方法① 重新定义视图"""
#
#     queryset = SKU.objects.all()
#     serializer_class = SKUSimpleSerializer
#     pagination_class = None


class SKUImagesView(ModelViewSet):
    """ SKU图片 增删改查 """

    queryset = SKUImage.objects.all().order_by("id")
    serializer_class = SKUImageSerializer
    pagination_class = MyPagination

    @action(methods=["get"], detail=False)
    def simple(self, request):
        """ 获取sku名称 --- 方法② 自定义action动作 """
        sku_model = SKU.objects.all()
        serializer = SKUSimpleSerializer(instance=sku_model, many=True)
        return Response(serializer.data)

    # TODO：上传图片到 FastDFS 方式① --- 在视图中重写 create (比较麻烦的方法)
    # 先将图片上传到 FastDFS，再将返回的图片索引id存入数据库
    # def create(self, request, *args, **kwargs):
    #     from fdfs_client.client import Fdfs_client
    #     from django.conf import settings
    #     import os
    #
    #     image_file = request.FILES.get("image")     # 文件对象
    #     image_byte = image_file.read()          # 文件字节数据
    #     sku_id = request.data.get('sku')
    #     sku_model = SKU.objects.get(id=sku_id)
    #
    #     conf_path = os.path.join(settings.BASE_DIR, "utils/client.conf")    # 配置文件路径
    #
    #     conn = Fdfs_client(conf_path)               # 实例化对象
    #     return_dict = conn.upload_by_buffer(image_byte)     # 上传到Fdfs
    #     """
    #     @return dict {
    #         'Group name'      : group_name,
    #         'Remote file_id'  : remote_file_id,
    #         'Status'          : 'Upload successed.',
    #         'Local file name' : '',
    #         'Uploaded size'   : upload_size,
    #         'Storage IP'      : storage_ip
    #     } if success else None
    #     """
    #     if not (return_dict and return_dict["Status"] == "Upload successed."):
    #         raise Exception("FastDFS上传图片失败")
    #     image = return_dict["Remote file_id"]
    #     sku_image_model = SKUImage.objects.create(sku=sku_model, image=image)
    #
    #     return Response({
    #         "id": sku_image_model.id,
    #         "sku": sku_id,
    #         # ImageField 类型的字段，需要通过该字段的.url属性来获取完整的图片链接
    #         "image": sku_image_model.image.url
    #     }, status=201   # 前端需要接受201状态
    #     )
